<?php

namespace app\api\controller;
use app\admin\model\Admin;
use app\admin\model\Detection;
use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use FPDF;
use think\Config;
use think\Db;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }

    public  function getInfo()
    {
        $id = $this->request->get('id');

        $model = new Detection();
        $info = $model->whereIn('id',$id)->select();

        if(empty($info)){
            $this->error('未查询到记录');
        }else{
            foreach ($info as $key => $value) {
                $detectionJson = json_decode($value['detection_json'],'true');
                foreach ($detectionJson as $k => $v){
                    $detectionJson[$k]['project_name'] = \app\admin\model\Project::where(['id'=>$v['project']])->value('name');
                    $detectionJson[$k]['method_name'] = \app\admin\model\Menthod::where(['id'=>$v['method']])->value('name');
                    $detectionJson[$k]['reagent_name'] = \app\admin\model\Reagent::where(['id'=>$v['name']])->value('name');
                }
                $info[$key]['detection_json'] = $detectionJson;
                if(!empty($value['admin_id'])){
                    $admin = Admin::where(['id'=>$value['admin_id']])->find();
                    if(empty($admin)){
                        $info[$key]['admin']['username'] =$value['admin_nickname'];
                    }else{
                        $admin['username'] = $admin['nickname'];
                        $info[$key]['admin'] =$admin;
                    }
                }else{
                    $info[$key]['admin'] = ['username'=>''];
                }
                $createuser = Admin::where(['id'=>$value['create_id']])->value('nickname');
                if(empty($createuser)){
                    $info[$key]['createuser'] = $value['create_nickname'];
                }else{
                    $info[$key]['createuser'] = $createuser;
                }
            }
            $idsstr = $id;
            if(strpos($id, ',') !== false){
                $idsarr = explode(',',$id);
                sort($idsarr);
                $idsstr = implode('-',$idsarr);
            }
            $pdfurl = Db::name('pdf_list')->where(['dete_id'=>$idsstr])->order('id','desc')->value('pdf_url');
            $this->success('',['info'=>$info,'pdfurl'=>$pdfurl]);
        }
    }


    public function uploadpdf(){
        $id = $this->request->param('id');

        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {

            $idsstr = $id;
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            if(strpos($id, ',') === false){
                $model = new Detection();
                $row = $model->where(['id'=>$id])->find();
                if(empty($row)){
                    $this->error("数据id不对");
                }
                $model->where(['id'=>$id])->update(['pdf_url'=>cdnurl($attachment->url, true)]);
            }else{
                $idsarr = explode(',',$id);
                sort($idsarr);
                $idsstr = implode('-',$idsarr);
            }
            Db::name('pdf_list')->insert([
               'dete_id'=>$idsstr,
               'pdf_url'=>cdnurl($attachment->url, true)
           ]);
            $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }

    }

    public function curl_get(){

        $url = cdnurl("/html2pdf/?id=14&show=1", true);
        $headers = array("Content-type: application/json;charset=UTF-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $output = curl_exec($curl);
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);//捕抓异常
        }
        curl_close($curl);
        return $output;

    }
    function curl_get_https(){
        $url  = cdnurl("/html2pdf/?id=14", true);
        // 初始化cURL会话
        $ch = curl_init();

// 设置cURL选项
        curl_setopt($ch, CURLOPT_URL, $url);            // 要访问的网站
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    // 将cURL获取的内容赋值到变量
        curl_setopt($ch, CURLOPT_HEADER, 0);            // 不输出header信息

// 执行cURL会话
        $response = curl_exec($ch);

// 关闭cURL会话
        curl_close($ch);

// 输出结果
        echo $response;die;
        $res = exec("curl $a",$opts);

        var_dump($opts); die;
//        $a = 'http://www.888.com/123.html';
        $opts = array(
            'http'=>array(
                'method'=>"GET",
                'header'=>
                    "Accept-language: zh-cn\r\n" .
                    "User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; 4399Box.560; .NET4.0C; .NET4.0E)" .
                    "Accept: *//*"
            )
        );
        $ctx = stream_context_create($opts);
        $x = file_get_contents($a,false,$ctx);
//        var_dump($x);die;
        $pdf = $this->pdf($x,'111111');
        var_dump($pdf);
    }

    public function pdf($html,$title)
    {
        vendor('Tcpdf.tcpdf');
        $file_name = time();
        $fileName = ROOT_PATH . 'public/uploads/pdf/'.$file_name;
        $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        // 设置打印模式
        //设置文件信息，头部的信息设置
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor( "河南社会保险单位网上业务大厅");
        $pdf->SetTitle($title);
        $pdf->SetSubject( 'TCPDF Tutorial');
        $pdf->SetKeywords( 'TCPDF, PDF, example, test, guide'); //设置关键字
        // 是否显示页眉
        $pdf->setPrintHeader( false);
        // 设置页眉显示的内容
        $pdf->SetHeaderData( 'logo.png', 60, 'baijunyao.com', '', array( 0, 64, 255), array( 0, 64, 128));
        // 设置页眉字体
        $pdf->setHeaderFont( Array( 'deja2vusans', '', '12'));
        // 页眉距离顶部的距离
        $pdf->SetHeaderMargin( '5');
        // 是否显示页脚
        $pdf->setPrintFooter( false);
        // 设置页脚显示的内容
        $pdf->setFooterData( array( 0, 64, 0), array( 0, 64, 128));
        // 设置页脚的字体
        $pdf->setFooterFont( Array( 'dejavusans', '', '10'));
        // 设置页脚距离底部的距离
        $pdf->SetFooterMargin( '10');
        // 设置默认等宽字体
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
        // 设置行高
        $pdf->setCellHeightRatio(1.3);
        // 设置左、上、右的间距
        $pdf->SetMargins( '10', '10', '10');
        // 设置是否自动分页 距离底部多少距离时分页
        $pdf->SetAutoPageBreak( TRUE, '15');
        // 设置图像比例因子
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
        if (@file_exists(dirname( __FILE__). '/lang/eng.php')) {
            require_once(dirname( __FILE__). '/lang/eng.php');
            $pdf->setLanguageArray($l);
        }
        $pdf->setFontSubsetting( true);
        $pdf->AddPage( "A4", "Landscape", true, true);
        // 设置字体
        $pdf->SetFont( 'stsongstdlight', '', 8, '', true);
        $pdf->writeHTML($html); //HTML生成PDF
//        $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
        $showType= 'F'; //PDF输出的方式。I，在浏览器中打开；D，以文件形式下载；F，保存到服务器中；S，以字符串形式输出；E：以邮件的附件输出。
        $pdf->Output( "{$fileName}.pdf", $showType);
        return 'http://'.$_SERVER['SERVER_NAME'].'/uploads/pdf/'.$file_name .'.pdf';
    }



    public function jsonlog(){
        $model = new Detection();
        $list = $model->select();
        foreach ($list as $key => $value){
            $date = date('Y-m-d',$value['create_time']);
            $startime = strtotime($date);
            $endtime = $value['create_time'];
            $num = $model->where("create_time > $startime and create_time < $endtime")->sum('num');
            $array = json_decode($value['detection_json'],true);
            $unit_id = $value['unit_id'];
            $unitModel = new \app\admin\model\Unit();
            $unit = $unitModel->where(['id'=>$unit_id])->find();
            foreach ($array as $k => &$v){
                $num++;
                    $v['code'] ='SNA'. str_pad($unit['id'], 4, '0', STR_PAD_LEFT).date('md').$num;
            }
            $model->where(['id'=>$value['id']])->update(['detection_json'=>json_encode($array,JSON_UNESCAPED_UNICODE)]);
        }
        $this->success();
    }
}
